package com.zhyt.intelligentpipeline.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhyt.intelligentpipeline.exception.CustomException;
import com.zhyt.intelligentpipeline.exception.ErrorBody;
import com.zhyt.intelligentpipeline.mapper.DeformationDetectionMapper;
import com.zhyt.intelligentpipeline.model.CorrosionDetection;
import com.zhyt.intelligentpipeline.model.DeformationDetection;
import com.zhyt.intelligentpipeline.model.Pipeline;
import com.zhyt.intelligentpipeline.service.DeformationDetectionService;
import com.zhyt.intelligentpipeline.service.PipelineService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeformationDetectionServiceImpl extends ServiceImpl<DeformationDetectionMapper,DeformationDetection> implements DeformationDetectionService {
    @Resource
    private PipelineService pipelineService;
    @Resource
    private DeformationDetectionMapper deformationDetectionMapper;

    @Override
    public List<DeformationDetection> getDeformationDetectionByPipelineID(String pipelineId) {
        Pipeline pipeline = pipelineService.getPipelineById(pipelineId);
        if(pipeline == null){
            throw CustomException.of(HttpStatus.BAD_REQUEST,new ErrorBody(550,"没有这条管线的信息"));
        }
        String initStationName = pipeline.getInitialStation();
        String endStationName = pipeline.getEndStation();

        LambdaQueryWrapper<DeformationDetection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeformationDetection::getEndStation,endStationName).eq(DeformationDetection::getInitialStation,initStationName);
        List<DeformationDetection> deformationDetection = deformationDetectionMapper.selectList(queryWrapper);
        //将腐蚀缺陷按照里程排序
        return deformationDetection.stream().sorted(Comparator.comparing(DeformationDetection::getMileage)).collect(Collectors.toList());
    }

    @Override
    public int getDeformationDetectionByCount(String pipelineId) {
        Pipeline pipeline = pipelineService.getPipelineById(pipelineId);
        if(pipeline == null){
            throw CustomException.of(HttpStatus.BAD_REQUEST,new ErrorBody(550,"没有这条管线的信息"));
        }
        String initStationName = pipeline.getInitialStation();
        String endStationName = pipeline.getEndStation();
        //获取该站点的所有腐蚀缺陷
        LambdaQueryWrapper<DeformationDetection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeformationDetection::getEndStation,endStationName).eq(DeformationDetection::getInitialStation,initStationName);
        return deformationDetectionMapper.selectList(queryWrapper).size();
    }
}
